/**
 * n8n 增强工作流工具
 * 提供更细粒度的节点操作，减少updateWorkflow操作出错的几率
 */

import type { ToolPackage } from '../../core/tool-registry.js';
import { createTool, field } from '../../core/tool-schema.js';
import { createErrorLogContext, logger } from '../../utils/logger.js';
import { N8NClient } from './client.js';
import { N8NError } from './errors.js';

// 创建客户端实例
const client = new N8NClient();

/**
 * 通用的MCP工具错误处理包装器
 */
async function withErrorHandling<T>(
  operation: string,
  apiCall: () => Promise<T>
): Promise<{
  success: boolean;
  error?: string;
  errorType?: string;
  statusCode?: number;
  data?: T;
  message?: string;
}> {
  try {
    const result = await apiCall();
    return {
      success: true,
      data: result,
    };
  } catch (error) {
    if (error instanceof N8NError) {
      logger.error(`n8n Enhanced Tools: ${operation} failed`, error.toLogContext());
      return {
        success: false,
        error: error.getUserMessage(),
        errorType: error.type,
        statusCode: error.statusCode,
      };
    }

    logger.error(`n8n Enhanced Tools: ${operation} failed`, createErrorLogContext(error));
    return {
      success: false,
      error: error instanceof Error ? error.message : String(error),
    };
  }
}

// ========== 节点精细操作工具 ==========

const addNodeToWorkflow = createTool()
  .name('n8n_add_node')
  .title('添加节点到工作流')
  .description('向指定工作流添加一个新节点，自动处理节点配置和ID生成')
  .version('1.0.0')
  .author('Test Case Writer Team')
  .category('n8n节点操作')
  .tags(['n8n', 'node', 'add'])
  .parameter('workflowId', field.required(field.string({ description: '目标工作流ID' })))
  .parameter(
    'nodeType',
    field.required(field.string({ description: '节点类型，如 "n8n-nodes-base.httpRequest"' }))
  )
  .parameter('nodeName', field.required(field.string({ description: '节点名称' })))
  .parameter(
    'position',
    field.optional(field.array(field.number(), { description: '节点位置 [x, y]，默认 [250, 300]' }))
  )
  .parameter('parameters', field.optional(field.object({}, { description: '节点参数配置' })))
  .parameter('credentials', field.optional(field.object({}, { description: '节点凭据配置' })))
  .build(async params => {
    return await withErrorHandling('Add node', async () => {
      // 获取当前工作流
      const workflow = await client.getWorkflow(params.workflowId);

      // 生成新节点ID
      const newNodeId = `node_${Date.now()}`;

      // 创建新节点
      const newNode = {
        id: newNodeId,
        name: params.nodeName,
        type: params.nodeType,
        typeVersion: 1, // 默认版本
        position: params.position || [250, 300],
        parameters: params.parameters || {},
        ...(params.credentials && { credentials: params.credentials }),
      };

      // 添加到现有节点数组
      const updatedNodes = [...(workflow.nodes || []), newNode];

      // 更新工作流
      const updated = await client.updateWorkflow(params.workflowId, {
        nodes: updatedNodes,
      });

      return {
        success: true,
        message: `成功添加节点 "${params.nodeName}" (${newNodeId}) 到工作流`,
        data: {
          workflow: updated,
          addedNode: newNode,
        },
      };
    });
  });

const removeNodeFromWorkflow = createTool()
  .name('n8n_remove_node')
  .title('从工作流中移除节点')
  .description('从指定工作流中移除指定节点，并自动清理相关连接')
  .version('1.0.0')
  .author('Test Case Writer Team')
  .category('n8n节点操作')
  .tags(['n8n', 'node', 'remove'])
  .parameter('workflowId', field.required(field.string({ description: '目标工作流ID' })))
  .parameter('nodeId', field.required(field.string({ description: '要移除的节点ID' })))
  .build(async params => {
    return await withErrorHandling('Remove node', async () => {
      // 获取当前工作流
      const workflow = await client.getWorkflow(params.workflowId);

      // 过滤掉指定节点
      const updatedNodes = (workflow.nodes || []).filter(node => node.id !== params.nodeId);

      // 清理连接中涉及该节点的部分
      const updatedConnections = { ...workflow.connections };

      // 移除该节点作为源的连接
      delete updatedConnections[params.nodeId];

      // 移除其他节点到该节点的连接
      Object.keys(updatedConnections).forEach(sourceNodeId => {
        const connections = updatedConnections[sourceNodeId];
        Object.keys(connections).forEach(outputType => {
          connections[outputType] = connections[outputType]
            .filter((connGroup: any) =>
              connGroup.filter((conn: any) => conn.node !== params.nodeId)
            )
            .filter((connGroup: any) => connGroup.length > 0);
        });
      });

      // 更新工作流
      const updated = await client.updateWorkflow(params.workflowId, {
        nodes: updatedNodes,
        connections: updatedConnections,
      });

      return {
        success: true,
        message: `成功从工作流中移除节点 "${params.nodeId}"`,
        data: {
          workflow: updated,
          removedNodeCount: (workflow.nodes?.length || 0) - updatedNodes.length,
        },
      };
    });
  });

const updateNodeInWorkflow = createTool()
  .name('n8n_update_node')
  .title('更新工作流中的节点')
  .description('更新工作流中指定节点的配置，只需提供要修改的字段')
  .version('1.0.0')
  .author('Test Case Writer Team')
  .category('n8n节点操作')
  .tags(['n8n', 'node', 'update'])
  .parameter('workflowId', field.required(field.string({ description: '目标工作流ID' })))
  .parameter('nodeId', field.required(field.string({ description: '要更新的节点ID' })))
  .parameter('name', field.optional(field.string({ description: '新的节点名称' })))
  .parameter('parameters', field.optional(field.object({}, { description: '新的节点参数' })))
  .parameter(
    'position',
    field.optional(field.array(field.number(), { description: '新的节点位置 [x, y]' }))
  )
  .parameter('credentials', field.optional(field.object({}, { description: '新的凭据配置' })))
  .parameter('disabled', field.optional(field.boolean({ description: '是否禁用节点' })))
  .parameter('notes', field.optional(field.string({ description: '节点备注' })))
  .build(async params => {
    return await withErrorHandling('Update node', async () => {
      const { workflowId, nodeId, ...updates } = params;

      // 获取当前工作流
      const workflow = await client.getWorkflow(workflowId);

      // 查找要更新的节点
      const nodeIndex = (workflow.nodes || []).findIndex(node => node.id === nodeId);
      if (nodeIndex === -1) {
        throw new Error(`节点 "${nodeId}" 未找到`);
      }

      // 更新节点
      const updatedNodes = [...(workflow.nodes || [])];
      const currentNode = updatedNodes[nodeIndex];

      updatedNodes[nodeIndex] = {
        ...currentNode,
        ...(updates.name && { name: updates.name }),
        ...(updates.parameters && {
          parameters: { ...currentNode.parameters, ...updates.parameters },
        }),
        ...(updates.position && { position: updates.position }),
        ...(updates.credentials && { credentials: updates.credentials }),
        ...(updates.disabled !== undefined && { disabled: updates.disabled }),
        ...(updates.notes && { notes: updates.notes }),
      };

      // 更新工作流
      const updated = await client.updateWorkflow(workflowId, {
        nodes: updatedNodes,
      });

      const updatedFields = [];
      if (updates.name) updatedFields.push('名称');
      if (updates.parameters) updatedFields.push('参数');
      if (updates.position) updatedFields.push('位置');
      if (updates.credentials) updatedFields.push('凭据');
      if (updates.disabled !== undefined) updatedFields.push('状态');
      if (updates.notes) updatedFields.push('备注');

      return {
        success: true,
        message: `成功更新节点 "${nodeId}"${
          updatedFields.length > 0 ? `，更新字段: ${updatedFields.join('、')}` : ''
        }`,
        data: {
          workflow: updated,
          updatedNode: updatedNodes[nodeIndex],
        },
      };
    });
  });

/**
 * 根据节点ID或名称查找节点
 */
function findNodeByIdOrName(nodes: any[], identifier: string): any {
  // 先按ID查找
  let node = nodes.find(n => n.id === identifier);
  if (node) return node;

  // 再按名称查找
  node = nodes.find(n => n.name === identifier);
  return node;
}

const connectNodes = createTool()
  .name('n8n_connect_nodes')
  .title('连接工作流节点')
  .description(
    '在工作流中的两个节点之间创建连接。\\n\\n**重要提示**：可以使用节点ID或节点名称，工具会自动处理转换。\\n\\n**连接类型说明**：\\n- main: 普通数据流连接\\n- ai_languageModel: 语言模型连接到AI Agent\\n- ai_tool: 工具连接到AI Agent\\n- ai_embedding: 嵌入模型连接\\n- ai_document: 文档连接\\n- ai_textSplitter: 文本分割器连接'
  )
  .version('2.0.0')
  .author('Test Case Writer Team')
  .category('n8n节点操作')
  .tags(['n8n', 'connection', 'connect'])
  .parameter('workflowId', field.required(field.string({ description: '目标工作流ID' })))
  .parameter(
    'sourceNodeId',
    field.required(field.string({ description: '源节点ID或名称（推荐使用名称以避免连接问题）' }))
  )
  .parameter(
    'targetNodeId',
    field.required(field.string({ description: '目标节点ID或名称（推荐使用名称以避免连接问题）' }))
  )
  .parameter(
    'sourceOutputType',
    field.optional(field.string({ description: '源节点输出类型，默认 "main"', default: 'main' }))
  )
  .parameter(
    'targetInputType',
    field.optional(field.string({ description: '目标节点输入类型，默认 "main"', default: 'main' }))
  )
  .parameter(
    'sourceOutputIndex',
    field.optional(field.number({ description: '源节点输出索引，默认 0', default: 0 }))
  )
  .parameter(
    'targetInputIndex',
    field.optional(field.number({ description: '目标节点输入索引，默认 0', default: 0 }))
  )
  .build(async params => {
    return await withErrorHandling('Connect nodes', async () => {
      // 获取当前工作流
      const workflow = await client.getWorkflow(params.workflowId);

      // 查找源节点和目标节点（支持ID或名称）
      const sourceNode = findNodeByIdOrName(workflow.nodes || [], params.sourceNodeId);
      const targetNode = findNodeByIdOrName(workflow.nodes || [], params.targetNodeId);

      if (!sourceNode) {
        throw new Error(`源节点 "${params.sourceNodeId}" 未找到`);
      }
      if (!targetNode) {
        throw new Error(`目标节点 "${params.targetNodeId}" 未找到`);
      }

      // **关键修复**：使用节点名称(name)而不是ID来建立连接
      const sourceNodeName = sourceNode.name;
      const targetNodeName = targetNode.name;

      // 构建连接配置
      const connections = { ...workflow.connections };

      if (!connections[sourceNodeName]) {
        connections[sourceNodeName] = {};
      }

      const outputType = params.sourceOutputType || 'main';
      if (!connections[sourceNodeName][outputType]) {
        connections[sourceNodeName][outputType] = [];
      }

      // 添加新连接
      const outputIndex = params.sourceOutputIndex || 0;
      if (!connections[sourceNodeName][outputType][outputIndex]) {
        connections[sourceNodeName][outputType][outputIndex] = [];
      }

      // 检查连接是否已存在
      const existingConnection = connections[sourceNodeName][outputType][outputIndex].find(
        (conn: any) =>
          conn.node === targetNodeName &&
          conn.type === (params.targetInputType || 'main') &&
          conn.index === (params.targetInputIndex || 0)
      );

      if (existingConnection) {
        return {
          success: true,
          message: `节点连接已存在: "${sourceNodeName}" -> "${targetNodeName}"`,
          data: { workflow },
        };
      }

      // 添加新连接（使用节点名称）
      connections[sourceNodeName][outputType][outputIndex].push({
        node: targetNodeName, // 关键：使用节点名称而非ID
        type: params.targetInputType || 'main',
        index: params.targetInputIndex || 0,
      });

      // 更新工作流
      const updated = await client.updateWorkflow(params.workflowId, {
        connections,
      });

      return {
        success: true,
        message: `成功连接节点: "${sourceNodeName}" -> "${targetNodeName}"`,
        data: {
          workflow: updated,
          connection: {
            source: { id: sourceNode.id, name: sourceNodeName },
            target: { id: targetNode.id, name: targetNodeName },
            type: outputType,
          },
        },
      };
    });
  });

const disconnectNodes = createTool()
  .name('n8n_disconnect_nodes')
  .title('断开工作流节点连接')
  .description(
    '断开工作流中两个节点之间的连接。\\n\\n**重要提示**：可以使用节点ID或节点名称，工具会自动处理转换。'
  )
  .version('2.0.0')
  .author('Test Case Writer Team')
  .category('n8n节点操作')
  .tags(['n8n', 'connection', 'disconnect'])
  .parameter('workflowId', field.required(field.string({ description: '目标工作流ID' })))
  .parameter(
    'sourceNodeId',
    field.required(field.string({ description: '源节点ID或名称（推荐使用名称以避免连接问题）' }))
  )
  .parameter(
    'targetNodeId',
    field.required(field.string({ description: '目标节点ID或名称（推荐使用名称以避免连接问题）' }))
  )
  .parameter(
    'sourceOutputType',
    field.optional(field.string({ description: '源节点输出类型，默认 "main"', default: 'main' }))
  )
  .build(async params => {
    return await withErrorHandling('Disconnect nodes', async () => {
      // 获取当前工作流
      const workflow = await client.getWorkflow(params.workflowId);

      // 查找源节点和目标节点（支持ID或名称）
      const sourceNode = findNodeByIdOrName(workflow.nodes || [], params.sourceNodeId);
      const targetNode = findNodeByIdOrName(workflow.nodes || [], params.targetNodeId);

      if (!sourceNode) {
        throw new Error(`源节点 "${params.sourceNodeId}" 未找到`);
      }
      if (!targetNode) {
        throw new Error(`目标节点 "${params.targetNodeId}" 未找到`);
      }

      // 使用节点名称而非ID
      const sourceNodeName = sourceNode.name;
      const targetNodeName = targetNode.name;

      const connections = { ...workflow.connections };
      const outputType = params.sourceOutputType || 'main';

      if (!connections[sourceNodeName] || !connections[sourceNodeName][outputType]) {
        return {
          success: true,
          message: `节点连接不存在: "${sourceNodeName}" -> "${targetNodeName}"`,
          data: { workflow },
        };
      }

      // 移除连接（使用节点名称匹配）
      connections[sourceNodeName][outputType] = connections[sourceNodeName][outputType]
        .map((connGroup: any) => connGroup.filter((conn: any) => conn.node !== targetNodeName))
        .filter((connGroup: any) => connGroup.length > 0);

      // 如果输出类型下没有连接了，删除该输出类型
      if (connections[sourceNodeName][outputType].length === 0) {
        delete connections[sourceNodeName][outputType];
      }

      // 如果节点没有任何连接了，删除该节点的连接配置
      if (Object.keys(connections[sourceNodeName]).length === 0) {
        delete connections[sourceNodeName];
      }

      // 更新工作流
      const updated = await client.updateWorkflow(params.workflowId, {
        connections,
      });

      return {
        success: true,
        message: `成功断开节点连接: "${sourceNodeName}" -> "${targetNodeName}"`,
        data: {
          workflow: updated,
          disconnection: {
            source: { id: sourceNode.id, name: sourceNodeName },
            target: { id: targetNode.id, name: targetNodeName },
            type: outputType,
          },
        },
      };
    });
  });

// ========== 安全更新包装器 ==========

const safeUpdateWorkflow = createTool()
  .name('n8n_safe_update_workflow')
  .title('安全更新工作流')
  .description('安全地更新工作流，提供自动备份、智能合并和错误恢复功能')
  .version('1.0.0')
  .author('Test Case Writer Team')
  .category('n8n工作流操作')
  .tags(['n8n', 'workflow', 'safe-update', 'backup', 'merge'])
  .parameter('workflowId', field.required(field.string({ description: '目标工作流ID' })))
  .parameter('name', field.optional(field.string({ description: '新的工作流名称' })))
  .parameter(
    'nodes',
    field.optional(
      field.array(field.object({}, { description: '节点配置数组（必须是完整节点结构）' }))
    )
  )
  .parameter('connections', field.optional(field.object({}, { description: '连接配置' })))
  .parameter('settings', field.optional(field.object({}, { description: '工作流设置' })))
  .parameter(
    'createBackup',
    field.optional(field.boolean({ description: '是否创建备份（默认 true）', default: true }))
  )
  .parameter(
    'autoRecover',
    field.optional(field.boolean({ description: '失败时是否自动恢复（默认 true）', default: true }))
  )
  .build(async params => {
    return await withErrorHandling('Safe update workflow', async () => {
      const { workflowId, createBackup = true, autoRecover = true, ...updates } = params;

      // 第一步：获取当前工作流作为备份
      const originalWorkflow = await client.getWorkflow(workflowId);
      let backupData = null;

      if (createBackup) {
        backupData = {
          ...originalWorkflow,
          backupTimestamp: new Date().toISOString(),
        };
        logger.info(`已创建工作流 ${workflowId} 的备份`);
      }

      try {
        // 第二步：智能合并更新数据
        const mergedData: any = {
          // 基础字段（保持原有值，如果用户提供了新值则覆盖）
          name: updates.name ?? originalWorkflow.name,
          nodes: updates.nodes ?? originalWorkflow.nodes,
          connections: updates.connections ?? originalWorkflow.connections,
          settings: updates.settings ?? originalWorkflow.settings,

          // 保留系统字段
          staticData: originalWorkflow.staticData,
        };

        // 第三步：验证节点完整性
        if (updates.nodes) {
          const validationErrors: string[] = [];

          updates.nodes.forEach((node: any, index: number) => {
            const requiredFields = ['id', 'name', 'type', 'typeVersion', 'position'];
            const missingFields = requiredFields.filter(field => !node[field]);

            if (missingFields.length > 0) {
              validationErrors.push(`节点 ${index + 1} 缺少必需字段: ${missingFields.join(', ')}`);
            }

            // 检查position是否是有效数组
            if (node.position && (!Array.isArray(node.position) || node.position.length !== 2)) {
              validationErrors.push(`节点 ${index + 1} 的position格式错误，应为 [x, y] 数组`);
            }
          });

          if (validationErrors.length > 0) {
            throw new Error(`节点验证失败：\n${validationErrors.join('\n')}`);
          }
        }

        // 第四步：执行更新
        const updatedWorkflow = await client.updateWorkflow(workflowId, mergedData);

        // 构建成功消息
        const changedFields = [];
        if (updates.name !== undefined) changedFields.push('名称');
        if (updates.nodes !== undefined) changedFields.push(`节点(${updates.nodes.length}个)`);
        if (updates.connections !== undefined) changedFields.push('连接');
        if (updates.settings !== undefined) changedFields.push('设置');

        const changesSummary =
          changedFields.length > 0 ? `已更新: ${changedFields.join('、')}` : '无更改';

        return {
          success: true,
          message: `工作流安全更新成功 - ${changesSummary}`,
          data: {
            workflow: updatedWorkflow,
            backup: createBackup
              ? { available: true, timestamp: backupData?.backupTimestamp }
              : null,
            changes: {
              fields: changedFields,
              nodeCount: updates.nodes?.length || originalWorkflow.nodes?.length || 0,
            },
          },
        };
      } catch (updateError) {
        logger.error(`工作流更新失败: ${(updateError as Error).message}`);

        // 第五步：错误处理和自动恢复
        if (autoRecover && backupData) {
          logger.info('尝试自动恢复到更新前状态...');

          try {
            // 恢复到备份状态（去除备份时间戳）
            const { backupTimestamp, ...restoreData } = backupData;
            await client.updateWorkflow(workflowId, restoreData);

            return {
              success: false,
              error: `更新失败，已自动恢复: ${(updateError as Error).message}`,
              message: '工作流已恢复到更新前状态',
              data: {
                recovered: true,
                originalError: (updateError as Error).message,
                backupRestored: true,
              },
            };
          } catch (recoveryError) {
            return {
              success: false,
              error: `更新失败且恢复失败: 原错误=${(updateError as Error).message}, 恢复错误=${
                (recoveryError as Error).message
              }`,
              message: '请手动检查工作流状态',
              data: {
                recovered: false,
                originalError: (updateError as Error).message,
                recoveryError: (recoveryError as Error).message,
              },
            };
          }
        } else {
          // 不自动恢复或没有备份
          throw new Error(`工作流更新失败: ${(updateError as Error).message}`);
        }
      }
    });
  });

// ========== 辅助工具 ==========

const getWorkflowNodeNames = createTool()
  .name('n8n_get_workflow_node_names')
  .title('获取工作流节点名称映射')
  .description(
    '获取工作流中所有节点的ID和名称映射关系，帮助正确建立连接。建议在使用连接工具前调用此工具获取准确的节点名称。'
  )
  .version('1.0.0')
  .author('Test Case Writer Team')
  .category('n8n辅助工具')
  .tags(['n8n', 'nodes', 'mapping', 'helper'])
  .parameter('workflowId', field.required(field.string({ description: '目标工作流ID' })))
  .build(async params => {
    return await withErrorHandling('Get workflow node names', async () => {
      const workflow = await client.getWorkflow(params.workflowId);

      const nodeMapping = (workflow.nodes || []).map(node => ({
        id: node.id,
        name: node.name,
        type: node.type,
        displayName: `"${node.name}" (${node.id})`,
      }));

      // 按类型分组显示
      const nodesByType = nodeMapping.reduce((acc, node) => {
        const category = node.type.includes('langchain')
          ? 'LangChain AI'
          : node.type.includes('trigger')
          ? 'Triggers'
          : node.type.includes('base')
          ? 'Core Nodes'
          : 'Other';
        if (!acc[category]) acc[category] = [];
        acc[category].push(node);
        return acc;
      }, {} as Record<string, any[]>);

      return {
        success: true,
        message: `工作流 "${workflow.name}" 包含 ${nodeMapping.length} 个节点`,
        data: {
          workflowName: workflow.name,
          totalNodes: nodeMapping.length,
          nodeMapping,
          nodesByType,
          connectionTip:
            '建议在连接节点时使用节点名称（name字段）而非ID，以确保连接正确显示在n8n界面中。',
        },
      };
    });
  });

// ========== 工作流智能重建工具 ==========

const rebuildWorkflowFromTemplate = createTool()
  .name('n8n_rebuild_workflow_from_template')
  .title('从模板重建工作流')
  .description('基于预定义模板重建工作流，适用于工作流结构损坏的情况')
  .version('1.0.0')
  .author('Test Case Writer Team')
  .category('n8n工作流修复')
  .tags(['n8n', 'workflow', 'rebuild', 'template'])
  .parameter('workflowId', field.required(field.string({ description: '目标工作流ID' })))
  .parameter(
    'templateType',
    field.required(
      field.string({
        description: '模板类型',
        enum: ['rag-basic', 'webhook-basic', 'chat-basic', 'custom'],
      })
    )
  )
  .parameter(
    'preserveSettings',
    field.optional(field.boolean({ description: '是否保留原有设置', default: true }))
  )
  .parameter(
    'customTemplate',
    field.optional(
      field.object({}, { description: '自定义模板配置（当templateType为custom时使用）' })
    )
  )
  .build(async params => {
    return await withErrorHandling('Rebuild workflow', async () => {
      // 获取当前工作流基本信息
      const currentWorkflow = await client.getWorkflow(params.workflowId);

      // 根据模板类型生成基础结构
      let templateNodes: any[] = [];
      let templateConnections: any = {};

      switch (params.templateType) {
        case 'rag-basic':
          templateNodes = [
            {
              id: 'chat-trigger-1',
              name: 'When chat message received',
              type: '@n8n/n8n-nodes-langchain.chatTrigger',
              typeVersion: 1.1,
              position: [-3008, 336],
              parameters: {
                public: true,
                initialMessages: '你好！这里是知识库。有什么问题我可以帮你解答。',
                options: {},
              },
            },
            {
              id: 'ai-agent-1',
              name: 'AI Agent',
              type: '@n8n/n8n-nodes-langchain.agent',
              typeVersion: 2,
              position: [-2752, 240],
              parameters: {
                options: {
                  systemMessage: '你是知识库助手，帮助用户解答问题。',
                },
              },
            },
          ];

          templateConnections = {
            'chat-trigger-1': {
              main: [
                [
                  {
                    node: 'ai-agent-1',
                    type: 'main',
                    index: 0,
                  },
                ],
              ],
            },
          };
          break;

        case 'webhook-basic':
          templateNodes = [
            {
              id: 'webhook-1',
              name: 'Webhook',
              type: 'n8n-nodes-base.webhook',
              typeVersion: 1.1,
              position: [250, 300],
              parameters: {
                httpMethod: 'POST',
                path: 'webhook',
                responseMode: 'onReceived',
                options: {},
              },
            },
          ];
          templateConnections = {};
          break;

        case 'chat-basic':
          templateNodes = [
            {
              id: 'chat-trigger-1',
              name: 'Chat Trigger',
              type: '@n8n/n8n-nodes-langchain.chatTrigger',
              typeVersion: 1.1,
              position: [250, 300],
              parameters: {
                public: true,
                initialMessages: '你好！我是AI助手。',
                options: {},
              },
            },
          ];
          templateConnections = {};
          break;

        case 'custom':
          if (params.customTemplate) {
            templateNodes = params.customTemplate.nodes || [];
            templateConnections = params.customTemplate.connections || {};
          }
          break;
      }

      // 构建新的工作流配置
      const newWorkflowConfig = {
        name: currentWorkflow.name,
        nodes: templateNodes,
        connections: templateConnections,
        settings: params.preserveSettings ? currentWorkflow.settings : { executionOrder: 'v1' },
      };

      // 更新工作流
      const updated = await client.updateWorkflow(params.workflowId, newWorkflowConfig);

      return {
        success: true,
        message: `成功使用 "${params.templateType}" 模板重建工作流，共 ${templateNodes.length} 个节点`,
        data: {
          workflow: updated,
          templateType: params.templateType,
          nodeCount: templateNodes.length,
        },
      };
    });
  });

// ========== 导出工具包 ==========

export const enhancedWorkflowTools: ToolPackage = {
  meta: {
    name: 'n8n-enhanced-workflow',
    version: '2.0.0',
    description:
      'n8n 增强工作流操作工具，提供精细的节点管理、安全更新和智能连接功能。自动处理节点ID到名称的转换，解决连接显示问题。',
    author: 'Test Case Writer Team',
  },
  tools: [
    addNodeToWorkflow,
    removeNodeFromWorkflow,
    updateNodeInWorkflow,
    connectNodes,
    disconnectNodes,
    safeUpdateWorkflow,
    rebuildWorkflowFromTemplate,
    getWorkflowNodeNames,
  ],
};
